const Config = require("./Config");
const UserCookie = require("./UserCookie");
const axios = require('axios');

class User extends UserCookie
{
    #userInfo =  {
        cookie : '',
        avatar_url : '',
        user_id : '',
        nickname : '',
    }

    /**
     *
     * @param  {string} cookie
     * @return {boolean}
     */
    setCookie(cookie)
    {
        return Promise.resolve()
            .then(() => super.setCookie(cookie))
            .then(res => {
                if (!res) return false;
                return this.#setUserFromApi();
            })
            .then(userInfo => !!userInfo);
    }

    async #setUserFromApi()
    {
        this.#userInfo = await this.#getProfileFromApi();
        return this.#userInfo;
    }

    async #getProfileFromApi()
    {
        try {
            const apiUrl = 'https://music.163.com/api/nuser/account/get';
            const headers = {
                'User-Agent': Config.userAgent,
                'Cookie': this.getCookie() ? `MUSIC_U=${this.getCookie()};` : '',
                'Referer': 'https://music.163.com/',
            };

            // 请求用户信息
            const response = await axios.get(apiUrl, { headers });
            const data = response.data;

            if (data && data.code === 200 && data.profile) {
                const userId = data.profile.userId;
                const nickname = data.profile.nickname;
                const avatarUrl = data.profile.avatarUrl;

                console.log(`UID: ${userId}, Name: ${nickname}`);
                return {
                    cookie : this.getCookie(),
                    avatar_url : avatarUrl,
                    user_id : userId,
                    nickname : nickname,
                };
            } else {
                console.log('获取用户信息失败:', data);
                return null;
            }
        } catch (err) {
            console.error('请求失败:', err);
        }
    }

    /**
     * 获取网易云用户信息
     *
     */
    async getProfile()
    {
        if (!this.#userInfo || this.#userInfo.user_id === '') {
            await this.#setUserFromApi();
        }
        return this.#userInfo;
    }


    async login() {
        const cookie = await this.getCookieFromQrcodeLogin();
        if (!cookie || cookie.length <= 0) return false;
        return this.setCookie(cookie);
    }


}


module.exports = User